import os
import argparse
from docx import Document
from docx.shared import Pt
from docx.enum.text import WD_PARAGRAPH_ALIGNMENT
import re

# 配置项
CONFIG = {
    'excluded_dirs': ['venv', 'node_modules', 'eyeOnKylinClient.spec', '.idea', '.venv', 'build', 'dist', 'myenv', '_pycache_', '1.py', 'receiverServer.py', 'test_get_client_Connection.py', 'gui.spec', 'main.spec'],
    'header_text': "G_Kylin_Tune软件",
    'font_name': 'TimesNew Roman',
    'font_size': 10.5
}

def setup_document():
    """设置Word文档的基本配置，包括样式和页眉。"""
    doc = Document()
    style = doc.styles['Normal']
    style.font.name = CONFIG['font_name']
    style.font.size = Pt(CONFIG['font_size'])

    section = doc.sections[0]
    header = section.header
    header_paragraph = header.paragraphs[0]
    header_paragraph.text = CONFIG['header_text']
    header_paragraph.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER

    return doc

def remove_empty_paragraphs(doc):
    """删除文档中的空段落。"""
    for paragraph in doc.paragraphs:
        if paragraph.text.strip() == "":
            p = paragraph._element
            p.getparent().remove(p)
            p._p = p._element = None

def remove_comments(content, file_extension):
    """根据文件扩展名删除代码中的注释。"""
    if file_extension == '.py':
        # 删除单行注释
        content = re.sub(r'#.*', '', content)
        # 删除多行注释
        content = re.sub(r"'''.*?'''", '', content, flags=re.DOTALL)
    elif file_extension == '.js' or file_extension == '.css':
        # 删除单行注释
        content = re.sub(r'//.*', '', content)
        # 删除多行注释
        content = re.sub(r'/\*.*?\*/', '', content, flags=re.DOTALL)
    elif file_extension == '.html':
        # 删除HTML注释
        content = re.sub(r'<!--.*?-->', '', content, flags=re.DOTALL)
    return content

def remove_empty_lines(content):
    """删除内容中的空行。"""
    lines = content.splitlines()
    non_empty_lines = [line for line in lines if line.strip()]
    return '\n'.join(non_empty_lines)

def process_files(doc, project_dir, only_py):
    """遍历项目目录及其子目录，处理源代码文件。"""
    for root, dirs, files in os.walk(project_dir):
        dirs[:] = [d for d in dirs if d not in CONFIG['excluded_dirs']]
        for file in files:
            if only_py and not file.endswith('.py'):
                continue
            if file.endswith(('.py', '.html', '.css', '.js')):
                file_path = os.path.join(root, file)
                file_name = os.path.basename(file_path)
                add_file_to_document(doc, file_name, file_path)

def add_file_to_document(doc, file_name, file_path):
    """将文件内容添加到Word文档中。"""
    paragraph = doc.add_paragraph(file_name)
    paragraph.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
    try:
        with open(file_path, 'r', encoding='utf-8') as f:
            content = f.read()
    except UnicodeDecodeError:
        try:
            with open(file_path, 'r', encoding='gbk') as f:
                content = f.read()
        except UnicodeDecodeError:
            content = '无法读取文件内容'
    except Exception as e:
        print(f'读取文件 {file_path} 时出错: {e}')
        content = '无法读取文件内容'

    content = remove_comments(content, os.path.splitext(file_name)[1])
    content = remove_empty_lines(content)
    doc.add_paragraph(content, style='Normal')

def main():
    """主函数，解析命令行参数并执行文件处理。"""
    parser = argparse.ArgumentParser(description='Process code files and generate a Word document.')
    parser.add_argument('--only-py', action='store_true', help='Only process .py files')
    args = parser.parse_args()

    # 提示用户输入项目地址和文档保存地址，使用当前目录作为默认值
    project_dir = input("请输入项目地址 (默认: 当前目录): ") or os.getcwd()
    output_file = input("请输入文档保存地址 (默认: 当前目录/output.docx): ") or os.path.join(os.getcwd(), 'output.docx')

    doc = setup_document()
    process_files(doc, project_dir, args.only_py)
    remove_empty_paragraphs(doc)
    doc.save(output_file)

if __name__ == "__main__":
    main()